import java.awt.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

import javax.swing.JOptionPane;

import redstone.xmlrpc.XmlRpcFault;
import net.bican.wordpress.Wordpress;

/**
Autore:Stefano Ricciardi
Rilasciato sotto licenza GNU LGPL 3.0
*/
public class IscrizioniManager {
	public static String settaggi="settings.dat";
	public static String settaggiDir="settingsDir.dat";
	public static String user="geicatu.dat";
	public static String pass="geicatp.dat";
	public static String filesito="sito.dat";
	public static String myUsername="";
	public static String myPassword="";
	public static String mySite="";
	
	
	public int getUltimoIdScaricato() throws IOException{
		File f=new File(settaggi);
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return 0;
		}else{
			FileReader freader=new FileReader(f);
			String inputDaFile="";
			int redt=-1;
			while((redt=freader.read())!=-1){
				inputDaFile+=((char)redt+"");
			}
			freader.close();
			if(!inputDaFile.equals("")){
				
				return new Integer(inputDaFile).intValue();
			}
		}
		
		return 0;
	}
	public int getNumNuoveIscrizioni(int lastId)throws IOException{
		HttpURLConnection con=HttpUtils.sendGetRequest(mySite+"statusmid.php?subs="+lastId);
		String ultimoId=HttpUtils.readSingleLineRespone();
		return new Integer(ultimoId).intValue();
		
	}
	
	public void setUltimoIdScaricato(int newId ) throws IOException{
		File f=new File(settaggi);
		FileWriter fw=new FileWriter(f);
		fw.write(newId+"");
		fw.close();
		
	}
	
	public int getLastIdFromWeb(String address) throws IOException{
		HttpURLConnection con=HttpUtils.sendGetRequest(mySite+"statusmid.php");
		String ultimoId=HttpUtils.readSingleLineRespone();
		return new Integer(ultimoId).intValue();
		//return 0;
	}
	
	
	
	public boolean getPdfIscrizioneFromWeb(int idIscrizione,String path) throws IOException{
		HashMap<String,String> hm=new HashMap<String, String>();
		hm.put("progressivo", ""+idIscrizione);
		hm.put("user", myUsername);
		hm.put("pass", myPassword);
		HttpUtils.sendPostRequest(mySite+"reportCatechismo.php", hm);
		String idiscrizione=idIscrizione<10?"000"+idIscrizione:idIscrizione<100?"00"+idIscrizione:idIscrizione<1000?"0"+idIscrizione:""+idIscrizione;
		HttpUtils.writeResponseAsBinary(path+File.separator+idiscrizione+"-ISCRIZIONE.pdf");
		
		try{
			byte[] encoded = Files.readAllBytes(Paths.get(path+File.separator+idiscrizione+"-ISCRIZIONE.pdf"));
			String content=new String(encoded);
			if(content.contains("Errore 404 Pagina non trovata")){
				File f=new File(path+File.separator+idiscrizione+"-ISCRIZIONE.pdf");
				f.delete();
			}
		}catch(Exception rre){
			rre.printStackTrace();
		}
		
		HttpUtils.disconnect();
		
		return true;
	}
	
	public static void main(String[] args){
		IscrizioniManager im=new IscrizioniManager();
		
		try {
			//boolean b=im.getPdfIscrizioneFromWeb(4);
			//System.out.println(im.getLastIdFromWeb(mySite+"stautsmid.php"));
			//im.setUltimoIdScaricato(4);
			System.out.println(im.getUltimoIdScaricato());
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getDir() throws IOException{
		File f=new File(settaggiDir);
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "";
		}else{
			FileReader freader=new FileReader(f);
			String inputDaFile="";
			int redt=-1;
			while((redt=freader.read())!=-1){
				inputDaFile+=((char)redt+"");
			}
			freader.close();
			if(!inputDaFile.equals("")){
				
				return inputDaFile;
			}
		}
		
		return "";
	}
	public void setUltimoIdScaricato(String newDir ) throws IOException{
		File f=new File(settaggiDir);
		FileWriter fw=new FileWriter(f);
		fw.write(newDir+"");
		fw.close();
		
	}
	
	public void setPassword(String password ) throws IOException{
		File f=new File(pass);
		FileWriter fw=new FileWriter(f);
		fw.write(password+"");
		fw.close();
		
	}
	public void setUsername(String username ) throws IOException{
		File f=new File(user);
		FileWriter fw=new FileWriter(f);
		fw.write(username+"");
		fw.close();
	}
	public void setUserEPass(String username,String password ) throws IOException{
		setUsername(username);
		setPassword(password);
	}
	public static String getUser() throws IOException{
		File f=new File(user);
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "";
		}else{
			FileReader freader=new FileReader(f);
			String inputDaFile="";
			int redt=-1;
			while((redt=freader.read())!=-1){
				inputDaFile+=((char)redt+"");
			}
			freader.close();
			if(!inputDaFile.equals("")){
				
				return inputDaFile;
			}
		}
		
		return "";
	}
	public static String getPass() throws IOException{
		File f=new File(pass);
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "";
		}else{
			FileReader freader=new FileReader(f);
			String inputDaFile="";
			int redt=-1;
			while((redt=freader.read())!=-1){
				inputDaFile+=((char)redt+"");
			}
			freader.close();
			if(!inputDaFile.equals("")){
				
				return inputDaFile;
			}
		}
		
		return "";
	}
	
	public static int accedi(){
		caricaUserEPass();
		
		String xmlRpcUrl = mySite+"xmlrpc.php";
		try {
			Wordpress wp = new Wordpress(myUsername, myPassword, xmlRpcUrl);
			wp.getUserInfo();
		} catch (MalformedURLException e2) {
			JOptionPane.showMessageDialog(null,"Devi inserire l'indirizzo corretto del sito e le credenziali di accesso.");
			return 2;
		} catch (XmlRpcFault e1) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(null,"Devi inserire delle credenziali valide per accedere al sito");
			return 2;
		}catch (Exception e) {
			return 3;
		}
		
		return 0;
	}
	
	public static void caricaUserEPass(){
		try{
			mySite=getSito();
			myUsername=getUser();
			myPassword=getPass();
		}catch(Exception rre){
			
		}
		
	}
	
	public void setSito(String sito ) throws IOException{
		File f=new File(filesito);
		FileWriter fw=new FileWriter(f);
		fw.write(sito+"");
		fw.close();
	}
	public static String getSito() throws IOException{
		File f=new File(filesito);
		if(!f.exists()){
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return "";
		}else{
			FileReader freader=new FileReader(f);
			String inputDaFile="";
			int redt=-1;
			while((redt=freader.read())!=-1){
				inputDaFile+=((char)redt+"");
			}
			freader.close();
			if(!inputDaFile.equals("")){
				return inputDaFile;
			}
		}
		return "";
	}
	
	public void azzeraTutto(Component component) throws IOException{
		int res=JOptionPane.showConfirmDialog(component,"Continuando cancellerai tutti i file pdf delle iscrizioni che hai sul tuo computer.\nPrima di cancellare tutte le iscrizioni è consigliato fare un salvataggio dei PDF\n che si desidera conservare. Per salvare i file annullare questa operazione e poi premere sul bottone 'Apri Cartella'.\n\nVuoi continuare con la cancellazione?");
		if(res!=0){
			return;
		}
		this.setUltimoIdScaricato(0);
		String dir=this.getDir();
		File directory=new File(dir);
		File[] files=directory.listFiles();
		for(File toDel : files){
			if(toDel.getName().toUpperCase().endsWith("-ISCRIZIONE.PDF") && toDel.getName().length()==19) {
				try{
					toDel.delete();
				}catch(Exception rre){
					
				}
			}
		}
		JOptionPane.showMessageDialog(component, "Il programma è pronto per il nuovo anno pastorale");
		
	}
	
}
